package com.xiaoyu.studyworkspace.common.websocketclient;

import cn.hutool.json.JSONUtil;
import com.xiaoyu.studyworkspace.common.kapaentity.websocket.*;
import com.xiaoyu.studyworkspace.pojo.AutoUser;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;


@Slf4j
public class SimpleSocketClient extends WebSocketClient {
    private AutoUser autoUser;


    public SimpleSocketClient(URI serverUri, AutoUser autoUser) {
        super(serverUri);
        this.autoUser = autoUser;
    }

    @SneakyThrows
    @Override
    public void onOpen(ServerHandshake handshakedata) {

        log.info("websocket客户端和服务器连接成功");
        //发送登录信息
        KapaSocket kapaSocket = new KapaSocket();
        kapaSocket.setCmdCode(1);
        kapaSocket.setCmdMerge(KapaCmdMerge.LOGIN);
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setInitId(this.autoUser.getInit_id());
        loginInfo.setSessionId(this.autoUser.getSession_id());
        kapaSocket.setData(JSONUtil.toJsonStr(loginInfo).getBytes());
        log.info("发送登录{}", kapaSocket);
        this.send(kapaSocket.toString().getBytes(StandardCharsets.UTF_8));
    }

    public void onMessage(ByteBuffer byteBuffer) {
        String toString = new String(byteBuffer.array());
        KapaSocket kapaSocket = JSONUtil.toBean(toString, KapaSocket.class);
        String data = new String(kapaSocket.getData());
        if (kapaSocket.getCmdMerge() == KapaCmdMerge.ROOM_INFO) {
            return;
        }
        log.info(toString);
        log.info(data);
        if (kapaSocket.getCmdMerge() == KapaCmdMerge.LOGIN) {
            KapaSocket kapaSocket1 = new KapaSocket();
            kapaSocket1.setCmdCode(1);
            kapaSocket1.setCmdMerge(KapaCmdMerge.CHANGE_ROOM);
            KapaChangeRoom kapaChangeRoom = new KapaChangeRoom();
            kapaChangeRoom.setNextRoomId(1);
            kapaChangeRoom.setPrevRoomId(0);
            kapaSocket1.setData(JSONUtil.toJsonStr(kapaChangeRoom).getBytes());
            this.send(kapaSocket1.toString().getBytes());
        }


    }

    @Override
    public void onMessage(String message) {

    }

    @Override
    public void onClose(int code, String reason, boolean remote) {

    }

    @Override
    public void onError(Exception ex) {

    }
}
